import { asyncRoutes, constantRoutes } from '@/router'

/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 */
function hasPermission(roles, route) {
  if (route.meta && route.meta.roles) {
    return roles.some(role => route.meta.roles.includes(role))
  } else {
    return true
  }
}

/**
 * 去除二级路由 解决多级路由页面缓存问题
 * @param routes asyncRoutes
 * @param prefix
 */
function deleteFakeParent(router, prefix) {
  var newRouter = { ...router }
  if (prefix) newRouter.path = prefix + '/' + router.path
  if (!router.children) return newRouter
  var children = []
  if (router.noCompoent) {
    router.children.forEach(route => {
      const item = deleteFakeParent(route, newRouter.path)
      if (Array.isArray(item)) {
        item.forEach(el => {
          children.push(el)
        })
      } else {
        children.push(item)
      }
    })
    newRouter = children
  } else {
    // debugger
    router.children.forEach(route => {
      const item = deleteFakeParent(route)
      if (Array.isArray(item)) {
        item.forEach(el => {
          children.push(el)
        })
      } else {
        children.push(item)
      }
    })
    newRouter.children = children
  }
  return newRouter
}

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routes, roles) {
  const res = []

  routes.forEach(route => {
    const tmp = { ...route }
    if (hasPermission(roles, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, roles)
      }
      res.push(tmp)
    }
  })

  return res
}

const state = {
  routes: [],
  addRoutes: [],
  realRoutes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  },
  SET_REAL_ROUTES: (state, routes) => {
    // 真实路由 将三级转为二级
    // state.addRoutes = routes
    state.realRoutes = constantRoutes.concat(routes)
  }
}

const actions = {
  generateRoutes({ commit }, roles) {
    // console.log(roles, 'permission')
    return new Promise(resolve => {
      let accessedRoutes
      if (roles.includes('admin')) {
        accessedRoutes = asyncRoutes || []
      } else {
        accessedRoutes = filterAsyncRoutes(asyncRoutes, roles)
      }
      console.log(accessedRoutes)
      commit('SET_ROUTES', accessedRoutes)
      const dropSecond = accessedRoutes.map(router => deleteFakeParent(router)) // 删除二级
      commit('SET_REAL_ROUTES', dropSecond)
      console.log(dropSecond, 'dropSecond')
      resolve(dropSecond)
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
